//
//  ZYCWisdomSourceFolderViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/9/23.
//

#import "ZYCWisdomSourceFolderViewController.h"
#import "BTImageTitleButton.h"
#import "XDSDropDownMenu.h"
#import "ZYCCreateFolderViewController.h"
#import "ZYCPublicFolderModel.h"
#import "ZYCSourceWisdonFileCell.h"
#import "ZYCSourceWisdonCenterCell.h"
#import "ZYCNoDataView.h"
#import "ZYCRecourceWidomFileDetailViewController.h"

@interface ZYCWisdomSourceFolderViewController ()<UIGestureRecognizerDelegate,XDSDropDownMenuDelegate,UITableViewDelegate,UITableViewDataSource,UIDocumentPickerDelegate>

@property (nonatomic, strong) BTImageTitleButton *rightButton;
@property (nonatomic, strong) XDSDropDownMenu *menu;
@property (nonatomic, strong) UIView *downMenuBgView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, copy) NSString *filePath;
@property (nonatomic, copy) NSString *fileType;
@property (nonatomic, assign) NSUInteger fileSize;
@property (nonatomic, strong) NSArray *fliterArray;

@end

@implementation ZYCWisdomSourceFolderViewController

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.titleString;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    [self.view addSubview:self.tableView];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.type == ZYCFolderTypePublic) {
        [self loadPublicFolderOrFileByLevel];
    }else{
        [self loadPersonFolderOrFileByLevel];
    }

}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCPublicFolderModel *model = self.dataSource[indexPath.section];
    if ([model.classType integerValue] == 1) {//文件夹
        ZYCSourceWisdonCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCSourceWisdonCenterCell class]) forIndexPath:indexPath];
        cell.model = self.dataSource[indexPath.section];
        return cell;
    }else{// 文件
        ZYCSourceWisdonFileCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCSourceWisdonFileCell class]) forIndexPath:indexPath];
        cell.model = self.dataSource[indexPath.section];
        return cell;
    }

}
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 17.0f;
    }
    return 10.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = HEX_RGB(@"#F9F9F9");
    return v;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v = [UIView new];
    v.backgroundColor = HEX_RGB(@"#F9F9F9");
    return v;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYCPublicFolderModel *model = self.dataSource[indexPath.section];
    if ([model.classType integerValue] == 1) {// 文件夹
        ZYCWisdomSourceFolderViewController *vc = [[ZYCWisdomSourceFolderViewController alloc] init];
        vc.titleString = model.name;
        vc.parentFolderId = [model.p_id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        ZYCRecourceWidomFileDetailViewController *vc = [[ZYCRecourceWidomFileDetailViewController alloc] init];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }

    
}

#pragma mark - action

- (void)clickRightAction:(UIButton *)sender{
    CGRect rect = sender.frame;
    rect.size.width = 150;
    rect.origin.y = kNavBarAndStatusBarHeight - 32;
    rect.origin.x = kScreenWidth - 150 - 14.0f;
    [self.menu showDropDownMenu:sender withButtonFrame:rect arrayOfTitle:self.fliterArray arrayOfImage:nil animationDirection:@"down"];
    [[UIApplication sharedApplication].keyWindow addSubview:self.downMenuBgView];
    [self.downMenuBgView addSubview:self.menu];
}


- (void)downMenuBgViewTap{
    if (self.menu.superview) {
        [self.menu hideDropDownMenuWithBtnFrame:self.rightButton.frame];
        [self.downMenuBgView removeFromSuperview];
    }
    
}

#pragma mark - XDSDropDownMenuDelegate
-(void) dropDownMenu:(XDSDropDownMenu *)dropDownMenu didSelectItemAtIndex:(NSInteger)index
{
    [self.downMenuBgView removeFromSuperview];
    if (index == 0) {
        ZYCCreateFolderViewController *vc = [[ZYCCreateFolderViewController alloc] init];
        vc.parentFolderId = self.parentFolderId;
        vc.type = self.type;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [self presentDocumentPickerViewController];
    }
}

- (void)presentDocumentPickerViewController{
    NSArray*types =@[
            @"public.data",
            @"org.openxmlformats.wordprocessingml.document",
            @"org.openxmlformats.presentationml.presentation",
            @"com.microsoft.powerpoint.ppt",
            @"com.microsoft.word.doc",
            @"com.microsoft.excel.xls",
            @"com.microsoft.powerpoint.pptx",
            @"com.microsoft.word.docx",
            @"com.microsoft.excel.xlsx",
            @"public.avi",
            @"public.3gpp",
            @"public.mpeg-4",
            @"com.compuserve.gif",
            @"public.jpeg",
            @"public.png",
            @"public.plain-text",
            @"com.adobe.pdf"
    ];

    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:documentPicker animated:YES completion:nil];
}

#pragma mark - UIDocumentPickerDelegate
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
    NSLog(@"用户取消了选择!");
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls{
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL * _Nonnull newURL) {
            NSError *error = nil;
            NSString *fileName = [newURL lastPathComponent];
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                  NSLog(@"文件读取出错: %@",error);
              }else{
                  NSLog(@"上传: %@",fileName);
                  if (fileData.length / 1000 > 50*1000 ) {
                      [MrjToast makeToast:@"单个文件不能超过50M" makeView:self.view];
                      return;
                  }
                  self.fileSize = fileData.length;
                  [self fileUploadWithFileName:fileName fileData:fileData];
              }
              [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    }else{
        NSLog(@"授权失败");
    }
}

#pragma mark - UIGestureRecognizerDelegate
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view == self.downMenuBgView) {
        return YES;
    }
    return NO;
}


#pragma mark - 网络请求
- (void)loadPublicFolderOrFileByLevel{
    NSDictionary *params = @{
        @"parentFolderId":@(self.parentFolderId)
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_publicFolderOrFileByLevel requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCPublicFolderModel class] json:responseObject[@"body"]];
                [self.dataSource addObjectsFromArray:array];
                if (self.dataSource.count == 0) {
                    self.tableView.hidden = YES;
                    self.noDataView.hidden = NO;
                }else{
                    self.tableView.hidden = NO;
                    self.noDataView.hidden = YES;
                    [self.tableView reloadData];
                }
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)loadPersonFolderOrFileByLevel{
    NSDictionary *params = @{
        @"parentFolderId":@(self.parentFolderId)
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_personFolderOrFileByLevel requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCPublicFolderModel class] json:responseObject[@"body"]];
                [self.dataSource addObjectsFromArray:array];
                [self.tableView reloadData];
                if (self.dataSource.count == 0) {
                    self.tableView.hidden = YES;
                    self.noDataView.hidden = NO;
                }
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

- (void)fileUploadWithFileName:(NSString *)fileName fileData:(NSData *)fileData {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/zd-system-service/%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"sdfz_url"],Common_Post_Upload];
    [[URLManager sharedURLManager] POST:urlStr parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //在此位置生成一个要上传的数据体
        [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:@"image/png"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                NSLog(@"上传完成:%@",responseObject);
                self.fileName = responseObject[@"body"][@"fileName"];
                self.filePath = responseObject[@"body"][@"url"];
                [self addFileByType:self.type];
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"上传失败%@",error);
        }];
}


- (void)addFileByType:(ZYCFolderType)type{
    if (type == ZYCFolderTypePublic) {
        [self addPublicFile];
    }else{
        [self addPersonFile];
    }
    
}

- (void)addPersonFile{
    NSDictionary *params = @{
        @"fileName":self.fileName,
        @"filePath":self.filePath,
        @"fileType":@"2",
        @"fileSize":@(self.fileSize),
        @"parentFolderId":@(self.parentFolderId)
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AddPersonFile requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"message"]];
                [self loadPersonFolderOrFileByLevel];
            }else{
                [MrjSVProgressHUD showErrorWithStatus:responseObject[@"message"]];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}


- (void)addPublicFile{
    NSDictionary *params = @{
        @"fileName":self.fileName,
        @"filePath":self.filePath,
        @"fileType":@"2",
        @"fileSize":@(self.fileSize),
        @"parentFolderId":@(self.parentFolderId)
    };
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_AddPublicFile requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            if (SUCCESS(responseObject[@"code"])) {
                [MrjSVProgressHUD showSuccessWithStatus:responseObject[@"message"]];
                [self loadPublicFolderOrFileByLevel];
            }else{
                [MrjSVProgressHUD showErrorWithStatus:responseObject[@"message"]];
            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
}

#pragma mark - getters

- (NSArray *)fliterArray {
    if (!_fliterArray) {
        _fliterArray =  @[@"新建文件夹",@"上传文件"];
    }
    return _fliterArray;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, kScreenHeight - kNavBarAndStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCSourceWisdonCenterCell class] forCellReuseIdentifier:NSStringFromClass([ZYCSourceWisdonCenterCell class])];
        [_tableView registerClass:[ZYCSourceWisdonFileCell class] forCellReuseIdentifier:NSStringFromClass([ZYCSourceWisdonFileCell class])];
    }
    return _tableView;
}

-(XDSDropDownMenu *)menu{
    if (!_menu) {
        _menu = [[XDSDropDownMenu alloc] init];
        _menu.backgroundColor = [UIColor yellowColor];
        _menu.textFont = kCustomFont(@"PingFangSC-Regular", 18.0f);
        _menu.textColor = HEX_RGB(@"#2D2D2D");
        _menu.delegate = self;
    }
    return _menu;
}

-(UIView *) downMenuBgView{
    if (!_downMenuBgView) {
        _downMenuBgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _downMenuBgView.backgroundColor = [UIColor colorWithHexString:@"ffffff" alpha:0.f];//透明
        _downMenuBgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(downMenuBgViewTap)];
        tap.numberOfTouchesRequired = 1;
        tap.numberOfTapsRequired = 1;
        tap.delegate = self;
        [_downMenuBgView addGestureRecognizer:tap];
    }
    return _downMenuBgView;
}

- (BTImageTitleButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [[BTImageTitleButton alloc] init];
        [_rightButton setTitle:@"添加" forState:UIControlStateNormal];
        [_rightButton setImage:[UIImage imageNamed:@"tj-1"] forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(clickRightAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
